package com.example.administrator.szb.fragments.shoucang;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.ShouCangActivity;
import com.example.administrator.szb.activity.base.BasePresenter;
import com.example.administrator.szb.activity.supei.SuPeiDeatilActivity;
import com.example.administrator.szb.bean.Messages;
import com.example.administrator.szb.fragments.base.MVPBaseFragment;
import com.example.administrator.szb.fragments.fragment_forTab.home.bean.Supeis;
import com.example.administrator.szb.fragments.shoucang.adapter.XMShouCangAdapter;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.JsonUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.Toasts;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.api.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by stone on 2017/12/28.
 */

public class XMShouCang extends MVPBaseFragment {
    private SmartRefreshLayout refreshLayout;
    private View error_net_ll;
    private TextView tv_net_error;
    private Button error_btn;
    ImageView iv_error2;
    private ListView listView;
    private LinearLayout footer_ll;
    private TextView all_or_no,del;
    private boolean isFirstEnter=true;
    private int current_page = 1;//列表当前页
    private int per_page = 10;//默认展示条数
    private XMShouCangAdapter adapter;
    private List lists=new ArrayList();
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_shoucang_jg, null);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(View view) {
        iv_error2 = view.findViewById(R.id.iv_error2);
        footer_ll = view.findViewById(R.id.footer_ll);
        all_or_no = view.findViewById(R.id.all_or_no);
        del = view.findViewById(R.id.del);
        refreshLayout = view.findViewById(R.id.zx_fragment_swiperefreshlayout);
        listView = view.findViewById(R.id.listView);
        error_net_ll = view.findViewById(R.id.error_net_ll);
        error_btn = view.findViewById(R.id.home_fragment_button_djcs_error);
        tv_net_error = view.findViewById(R.id.tv_net_error);
    }
    private boolean isSelectAll = false;
    @Override
    protected void initEvent() {
        all_or_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelectAll){
                    isSelectAll = false;
                    all_or_no.setText("全选");
                    adapter.setSelectNo();
                }else {
                    isSelectAll = true;
                    all_or_no.setText("全不选");
                    adapter.setSelectAll();

                }
            }
        });
        del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //先判断是否为空
                if (adapter.getSelectList().size()>0){
                    //请求删除

                    new AlertDialog.Builder(context)
                            .setTitle("提示")
                            .setMessage("确认删除？")
                            .setNegativeButton("取消",null)
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String str = "";
                                    for (int i=0;i<adapter.getSelectList().size();i++){
                                        Supeis articleBean = (Supeis) adapter.getSelectList().get(i);
                                        str+=articleBean.getId()+",";
                                    }
                                    requestDel(str);
                                }
                            }).show();

                }else {
                    DialogUtil.showToast(context,"请选择要删除的选项");
                }
            }
        });



        refreshLayout.setEnableLoadMore(true);//是否启用上拉加载功能
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);//是否在列表不满一页时候开启上拉加载功能


        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                int p = current_page+1;
                requestReferList(1, p,per_page);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                QTLog.e("刷新");
                requestReferList(0, 1,per_page);
            }
        });
        error_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshLayout.autoRefresh();
                requestReferList(0, 1,per_page);
            }
        });
    }

    @Override
    protected void initData() {

        adapter = new XMShouCangAdapter(lists,context);
        adapter.setOnItemClick(new ItemsClickListener() {
            @Override
            public void onItemClick(int pos) {
                Intent intent = new Intent(context,SuPeiDeatilActivity.class);
                intent.putExtra("id",((Supeis)lists.get(pos)).getId());
                startActivity(intent);
            }
        });
        notifys();
        listView.setAdapter(adapter);
        if (isFirstEnter) {
            isFirstEnter = false;
            refreshLayout.autoRefresh();
        }
    }

    /**
     *
     * @param type 其中传入0代表刷新，1代表加载更多
     * @param page
     * @param count
     */
    private void requestReferList(final int type, int page, int count){

        error_net_ll.setVisibility(View.GONE);

        Map<String,Object> params = new HashMap<>();
        params.put("code", HttpUtil.getParam());
        params.put("id", SPUtils.getUserId());
        params.put("page",page);
        params.put("per_page",per_page);
        HttpUtils.post2(activity,URLAddress.SUPEI_MYLIST_COLLECT, params,0, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                str = str.replace("\"data\":{}","\"data\":[]");
                str = str.replace("\"data\":\"没有数据\"","\"data\":[]");
                str = str.replace("\"0\":[]","\"0\":{}");
                str = str.replace("\"1\":","\"first\":");
                str = str.replace("\"0\":","\"zero\":");
                Messages messages = JsonUtils.getMessages2(str);
                if (messages.getResult()==1){
                    str = JsonUtils.JsonParse(messages);
                    List list = JSON.parseArray(str, Supeis.class);
                    if (type==1){
                        //加载更多
                        refreshLayout.finishLoadmore();

                        current_page++;
                        if (list.size()<per_page){

                            //没有更多了
                            refreshLayout.setEnableLoadMore(false);

                        }
                    }else {
                        lists.clear();

                        //刷新
                        refreshLayout.finishRefresh();
                        refreshLayout.setEnableLoadMore(true);
                        current_page=1;
                    }
                    lists.addAll(list);
                    if (lists.size()==0){
                        tv_net_error.setText("你还没有收藏项目");

                        iv_error2.setImageResource(R.mipmap.no_data_icon);
                        error_btn.setVisibility(View.GONE);
                        error_net_ll.setVisibility(View.VISIBLE);
                    }
                    initAdater();
                }





            }

            @Override
            public void onFailure(int requestCode, String str) {
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadmore();
                tv_net_error.setText("网络异常,无法连接网络");

                iv_error2.setImageResource(R.mipmap.error_icon);
                error_btn.setVisibility(View.VISIBLE);
                error_net_ll.setVisibility(View.VISIBLE);
            }
        });
    }
    private void initAdater(){
        if (adapter==null){
            adapter = new XMShouCangAdapter(lists,context);
            listView.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }
    }
    public void notifys(){
        QTLog.e("ssssss");
        //显示/隐藏 复选框按钮和底部选项
        if (ShouCangActivity.canShowCheckBox){
            footer_ll.setVisibility(View.VISIBLE);
            adapter.notifyDataSetChanged();
        }else {
            footer_ll.setVisibility(View.GONE);
            adapter.setSelectNo();
        }
    }

    private void requestDel(String ids){
        Map<String,Object> params = new HashMap<>();
        params.put("code",HttpUtil.getParam());
        params.put("uid",SPUtils.getUserId());
        params.put("ids",ids);
        params.put("type",1);
        HttpUtils.post(activity,URLAddress.CANCLECOLLECTS, params, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {

                ShouCangActivity.canShowCheckBox = false;
                ((ShouCangActivity)getActivity()).notifyFrgament();
                Toasts.show(context,"操作成功",1000);
                requestReferList(0,1,per_page);

            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });
    }
}